package com.itheima.tlias84.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.tlias84.config.AliyunOssConfig;
import jakarta.annotation.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Resource
public class UploadUtil {

    @Resource
    static AliyunOssConfig ossConfig;

    private UploadUtil() {  }

    public static String FileUpload(MultipartFile file) {
        //文件名
        String originalFilename = file.getOriginalFilename();
        //拆分文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成不重复UUID
        String uuid = UUID.randomUUID().toString();

        //阿里云OSS访问路径endpoint
        String endpoint = ossConfig.getEndpoint();
        //Bucket名称
        String bucketName = ossConfig.getBucketName();
        //填写Object完整路径，完整路径中不能包含Bucket名称，例如exampleDir/exampleObject.txt。
        String objectName = uuid + suffix;
        //创建OSSClient实例对象，指定访问密钥
        OSS ossClient = new OSSClientBuilder().build(endpoint, ossConfig.getAccessKeyId()
                , ossConfig.getSecretAccessKey());

        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            String url = ossConfig.getUrl() + objectName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
